package com.hanshg.cherry.security.authentication;

import com.hanshg.cherry.dto.LoginUser;
import com.hanshg.cherry.mapper.PermissionMapper;
import com.hanshg.cherry.model.SysPermission;
import com.hanshg.cherry.model.SysUser;
import com.hanshg.cherry.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author hanshg
 * @date 2021/8/11
 */
@Service
@Slf4j
@Qualifier("mobileUserDetailsService")
public class MobileUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * Locates the user based on the username. In the actual implementation, the search
     * may possibly be case sensitive, or case insensitive depending on how the
     * implementation instance is configured. In this case, the <code>UserDetails</code>
     * object that comes back may have a username that is of a different case than what
     * was actually requested..
     *
     * @param username the username identifying the user whose data is required.
     * @return a fully populated user record (never <code>null</code>)
     * @throws UsernameNotFoundException if the user could not be found or the user has no
     *                                   GrantedAuthority
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库中取出用户信息
        SysUser user = userService.getUserByPhone(username);

        // 判断用户是否存在
        if (user == null) {
            throw new UsernameNotFoundException("该手机号码尚未注册,请先注册账户");
        }

        // 添加权限
        LoginUser loginUser = new LoginUser();
        BeanUtils.copyProperties(user, loginUser);

        List<SysPermission> permissions = permissionMapper.listByUserId(user.getId());
        loginUser.setPermissions(permissions);

        // 返回UserDetails实现类
        return loginUser;
    }
}
